<?php

namespace app\api\logic;

use app\admin\model\article\Article;
use app\basic\BaseLogic;
use app\api\model\UserMemberDownloadLog;
use think\facade\Db;

class DownloadLogic extends BaseLogic
{
    protected $error;

    public function __construct()
    {
        $this->model = new UserMemberDownloadLog();
    }

    /**
     * 获取下载记录列表
     */
    public function getDownloadList($userId, $params)
    {
        // 参数处理
        $page = !empty($params['page']) ? intval($params['page']) : 1;
        $limit = !empty($params['limit']) ? intval($params['limit']) : 10;

        // 获取列表数据
        $list = $this->model->getList($userId, $page, $limit);
        
        // 获取总记录数
        $total = $this->model->getCount($userId);


        return [
            'list' => $list,
            'total' => $total,
            'page' => $page,
            'limit' => $limit
        ];
    }

    /**
     * 获取下载统计
     */
    public function getDownloadStats($userId)
    {
        // 本月时间范围
        $monthStart = strtotime(date('Y-m-01'));
        $monthEnd = strtotime(date('Y-m-01', strtotime('+1 month'))) - 1;

        // 本月下载次数
        $monthCount = $this->model->getCountByDate($userId, $monthStart, $monthEnd);

        // 总下载次数
        $totalCount = $this->model->getCount($userId);

        return [
            'month_count' => $monthCount,
            'total_count' => $totalCount
        ];
    }

    /**
     * 格式化文件大小
     */
    protected function formatFileSize($size)
    {
        if ($size == 0) {
            return '0B';
        }
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];
        $pow = floor(log($size, 1024));
        $pow = min($pow, count($units) - 1);
        
        $size /= pow(1024, $pow);
        return round($size, 2) . $units[$pow];
    }

    /**
     * 添加下载记录
     * @param int $userId 用户ID
     * @param array $params 参数
     * @return bool|array
     */
    public function addDownload($userId, $params)
    {
        Db::startTrans();
        try {
            // 参数验证
            $validate = new \think\Validate();
            $validate->rule([
                'article_id' => 'require|number',
            ]);
            if (!$validate->check($params)) {
                 $this->setError($validate->getError());
                 return false;
            }

            // 检查文章是否存在
            $article = (new Article())->where('id', $params['article_id'])->find();
            if (!$article) {
                 $this->setError('文档不存在');
                 return false;
            }
            // 创建下载记录
            $result = $this->model->create([
                'user_id' => $userId,
                'doc_id' => $params['article_id'],
                'title' => $article['title'],
                'create_time' => time(),
                'download_time' => time(),
            ]);
            if (!$result) {
                throw new \Exception('添加下载记录失败');
            }
            Db::commit();
            return [
                'id' => $result['id'],
                'title' => $article['title'],
            ];
        } catch (\Exception $e) {
            Db::rollback();
            $this->setError($e->getMessage());
            return false;
        }
    }


    public function setError($error)
    {
        $this->error = $error;
    }

    public function getError()
    {
        return $this->error;
    }
} 